﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;
using SDT.Systems;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 13/06/2011
    /// Description: The class product controller
    /// Modified by Vietlv
    /// </summary>
	[RoleHelper(Roles = RoleSystem.Product)]
    public class ProductController : Controller
    {
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        
        #region GET: /Product/
        public ActionResult Index(int? page)
        {
            try
            {
                    if (page == null)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("product.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("product.orderDir", "orderDir", "desc").ToString();
                    var productTypeID = Convert.ToInt32(UserState.getUserStateFromRequest("product.ProductType", "TypeID", 0)); // Inserted by Vietlv (26/07/2011)
                    int catID = Convert.ToInt32(UserState.getUserStateFromRequest("product.CatID", "CatID", 0));
                    string strHot = UserState.getUserStateFromRequest("product.CurrentHotStatus", "CurrentHotStatus", "").ToString();
                    string strPub = UserState.getUserStateFromRequest("product.CurrentPubStatus", "CurrentPubStatus", "").ToString();
                    string keyword = UserState.getUserStateFromRequest("product.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("product.pageSize", "PageSize", 20).ToString());

                    int? currentPub = null;
                    if (!string.IsNullOrEmpty(strPub))
                        currentPub = Convert.ToInt32(strPub);

                    int? currentHot = null;
                    if (!string.IsNullOrEmpty(strHot))
                        currentHot = Convert.ToInt32(strHot);

                    var pros = eDataContext.Products
                        .Where(p => productTypeID > 0 ? p.TypeID == productTypeID : true) // Inserted by Vietlv (26/07/2011)
                        .Where(p => (catID > 0 ? p.CatID == catID : true))
                        .Where(p => currentHot.HasValue ? p.HotYN == (currentHot.HasValue && currentHot.Value == 1 ? true : false) : true)
                        .Where(p => currentPub.HasValue ? p.PubYN == (currentPub.HasValue && currentPub.Value == 1 ? true : false) : true)
                        .Where(p => (string.IsNullOrEmpty(keyword) ? true :
                            (p.Title.ToLower().Contains(keyword.ToLower().Trim()) ||
                            p.Title.ToLower().Contains(keyword.ToLower().Trim()) ||
                            p.Title.ToLower().Contains(keyword.ToLower().Trim())
                        )))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    List<ProductCategory> categories = eDataContext.ProductCategories
                                                    .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                    .ToList();
                    
                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;
                    var listProductTypes = eDataContext.ProductTypes.ToList();
                    return View(new ProductViewModel
                    {
                        Products = pros,
                        Categories = categories,
                        CurrentCat = catID,
                        CurrentHotStatus = currentHot,
                        CurrentPubStatus = currentPub,
                        Keyword = keyword,
                        ProductTypes = listProductTypes,        // Inserted by Vietlv (26/07/2011)
                        CurrentProductType = productTypeID,     // Inserted by Vietlv (26/07/2011)
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Product/Details/5
        public ActionResult Details(int id)
        {
            try
            {
                    // product detail
                    Product pro = eDataContext.Products.Where(p => p.ID == id).FirstOrDefault();

                    // product category
                    List<ProductCategory> categories = eDataContext.ProductCategories
                                                    .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                    .ToList();
                    
                    // city
                    List<SelectListItem> listC = eDataContext.Cities
                                                    .Select(c => new SelectListItem()
                                                    {
                                                        Value = c.ID.ToString(),
                                                        Text = c.Name
                                                    }).ToList();

                    // district
                    List<SelectListItem> listD = eDataContext.Districts
                                                    .Where(d => d.CityID == pro.CityID)
                                                    .Select(d => new SelectListItem()
                                                    {
                                                        Value = d.ID.ToString(),
                                                        Text = d.Name
                                                    }).ToList();

                    // product attribute
                    var listPAtt = eDataContext.ProductAttributes.ToList();

                    // product attribute value
                    var listPAttID = eDataContext.ProductAttributeValues.Where(pV => pV.ProductID == id).Select(pV => pV.AttributeID).ToList();

                    // product image
                    List<string> listF =pro.AddDate != null? Uploads.GetFile(id, Settings.Default.SiteRootPath, Settings.Default.DocumentInArticleRootPath, Settings.Default.ProductFormatSubPath, pro.AddDate.Value) : null; // Modified by Vietlv (isert confident pro.AddDate = null)
                    // List Direction
                    var listDirection = Utils.StringToDictionary(Settings.Default.ProductDirection.ToString(), ",");
                    var currentDirection = "";
                    foreach (var itemDirection in listDirection)
                    {
                        var itemKey = Convert.ToInt32(itemDirection.Key);
                        if (pro.Direction != null && itemKey == int.Parse(pro.Direction)) currentDirection = itemDirection.Value.ToString();
                    }
                    return View(new ProductInputModel
                    {
                        Categories = categories,
                        ListCity = listC,
                        Product = pro,
                        ListDistrict = listD,
                        CityID = pro.CityID,
                        DistrictID = pro.DistrictID,
                        CatID = pro.CatID,
                        TypeID = pro.TypeID,
                        ListProductAtribute = listPAtt,
                        ListProductAttributeID = listPAttID,
                        ListFile = listF,
                        CurrentDirection = currentDirection,
                        ImageRootUrl = Settings.Default.SiteRootUrl
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion
        
        #region GET: /Product/Create
        public ActionResult Create()
        {
            try
            {
                    List<SelectListItem> listC = eDataContext.Cities
                                                    .Select(c => new SelectListItem()
                                                    {
                                                        Value = c.ID.ToString(),
                                                        Text = c.Name
                                                    }).ToList();
                    var listPAtt = eDataContext.ProductAttributes.ToList();
                    List<SelectListItem> listType = eDataContext.ProductTypes
                                                    .Select(t => new SelectListItem()
                                                    {
                                                        Text = t.Name,
                                                        Value = t.ID.ToString()
                                                    }).ToList();
                   
                    // Created by Vietlv
                    // Created date: 29/07/2011
                    // Description: Select list ProductDirection, ProductExpire  of product
                    var listProductDirection = Utils.StringToDictionary(Settings.Default.ProductDirection.ToString(), ",");
                    var listProductExpire = Utils.StringToDictionary(Settings.Default.ProducExpire.ToString(), ",");
                    var listCurrency = Utils.StringToDictionary(Settings.Default.ListCurrency.ToString(), ",");
                    var listUnitCost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",");
                    var usermanager = UserManager.GetUser(UserManager.GetUserId(), true);
                
                    return View(new ProductInputModel
                    {
                        ListCity = listC,
                        ListProductAtribute = listPAtt,
                        ListType = listType,
                        listProductDirection = listProductDirection,
                        listProductExpire = listProductExpire,
                         ListCurrency= listCurrency,
                        ListUnitCost = listUnitCost
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Product/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(ProductInputModel m)
        {
            try
            {
                if (ModelState.IsValid)
                {
                        UpdateModel(m);
                        var exDate =Convert.ToInt32(Request["ExpireDateTime"]);
                       
                        m.Product.ExpireDate = DateTime.Now.AddDays(exDate); 
                        m.Product.AddBy = UserManager.GetUserId();
                        m.Product.AddDate = DateTime.Now;
                        #region cost convert
                       // Case currency is "VND"
                        if (m.Product.CurrencyID == 1)
                        {
                            //Case unit cost is VND/m2
                            if (m.Product.UnitCostID == 1 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                m.Product.TotalCost = (decimal)m.Product.Area.Value * m.Product.Cost;                     // from  m.Product.UnitCost = costTypeID + new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2)  
                            }                                                                                             // To m.Product.UnitCost =new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2);   
                            // Case unit cost is VND/m2/tháng
                            if (m.Product.UnitCostID == 2 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }  
                                //var ttCost = Convert.ToDecimal(Request["Product.Cost"]);
                                m.Product.TotalCost = (decimal)m.Product.Area.Value * m.Product.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                            }
                            // Case unit cost is VND/tổng diện tích
                            if (m.Product.UnitCostID == 3 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                m.Product.TotalCost = m.Product.Cost;
                            }
                            m.Product.CurrencyName = "VND";
                        }
                        // Case currency is "USD"
                        if (m.Product.CurrencyID == 2)
                        {
                            //Case unit cost is USD/m2
                            if (m.Product.UnitCostID == 1 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Area.Value * m.Product.Cost.Value;
                            }
                            // Case unit cost is USD/m2/tháng
                            if (m.Product.UnitCostID == 2 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                m.Product.TotalCost = int.Parse(Settings.Default.USD)*(decimal)m.Product.Area.Value * m.Product.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                            }
                            //Case unit cost is USD/Tổng
                            if (m.Product.UnitCostID == 3 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Cost.Value;
                            }
                            m.Product.CurrencyName = "USD";
                        }

                        if (m.Product.TotalCost.HasValue)
                        {
							//Binhlv Lay ConvertPriceID Phu hop
                           // string conPri = (m.Product.TotalCost.Value / int.Parse(Settings.Default.UnitConvert)).ToString();
							m.Product.ConvertPrice1 = GetConvertPrice(m.Product.TotalCost.Value, m.Product.TypeID);//byte.Parse(conPri.Substring(0, conPri.IndexOf(".")));
                        }
						//Binhlv
						// Khoang dien tich
						if(m.Product.Area.HasValue)
						{
                            int typeid = m.Product.TypeID;
                            var area = m.Product.Area.Value;
                            m.Product.ConvertArea1 = GetConvertArea(area, typeid);
						}
                        #endregion

                        eDataContext.Products.InsertOnSubmit(m.Product);
                        eDataContext.SubmitChanges();

                        HttpPostedFileBase fileImage = Request.Files["ImagePaths"];
                        if (fileImage != null && fileImage.ContentLength > 0)
                        {
                            m.Product.ImagePath = Path.GetFileName(fileImage.FileName);
                            Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ProductRootPath), "" + m.Product.ID);
                        }
                        eDataContext.SubmitChanges();

                        #region product attribute
                        List<short> listProductAttributeID = Request["ProductAttributeValue"].Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(i => short.Parse(i)).ToList();
                        foreach (short id in listProductAttributeID)
                        {
                            ProductAttributeValue proAttValue = new ProductAttributeValue();

                            proAttValue.AttributeID = id;
                            proAttValue.ProductID = m.Product.ID;
                            proAttValue.Value = "1";

                            eDataContext.ProductAttributeValues.InsertOnSubmit(proAttValue);
                            eDataContext.SubmitChanges();
                        }

                        #endregion

                        #region Upload File
                        foreach (string inputTagName in Request.Files)
                        {
                            HttpPostedFileBase file = Request.Files[inputTagName];
                            if (file.ContentLength > 0 && inputTagName != "ArticleImage")
                            {
                                string filePath = string.Empty;
                                string subPath = string.Format(Settings.Default.ProductFormatSubPath, m.Product.AddDate.Value.Year, m.Product.AddDate.Value.Month, m.Product.AddDate.Value.Day, m.Product.ID);
                                if (!Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath))
                                {
                                    // If it doesn't then we just create it before going any further
                                    Directory.CreateDirectory(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath);
                                }
                                filePath = Path.Combine(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath, file.FileName);
                                file.SaveAs(filePath);
                            }
                        }
                        #endregion

                        return RedirectToAction("Index");
                    }
                    else
                    {
                        throw new Exception("Dữ liệu nhập không đúng.");
                    }
            }
            catch (Exception exp)
            {
                if (exp.Message.Contains("out of range"))  // Vietlv
                {
                    ViewData[Messages.MessageInfo] = "Tổng giá trị của bất động sản đã vượt quá mức con số cho phép. Vui xem xét lại!";
                    return View();
                }
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion
		
        #region Binhlv/ GetConvertPrice
		private ConvertPrice GetConvertPrice(decimal TotalPrice , int TypeProduct)
		{
			try
			{
				if (TotalPrice < 0) throw new NotSupportedException();
                var maxArea = eDataContext.ConvertPrices
                    .Where(e => e.TypeID == TypeProduct)
                    .OrderByDescending(e => e.MaxValue)
                    .FirstOrDefault();
                if (TotalPrice > maxArea.MaxValue)
                {
                    return maxArea;
                }
                var CurrentConvertPrice = eDataContext.ConvertPrices
                                        .Where(ca => ca.TypeID == TypeProduct)
                                        .Where(c => c.MinValue < TotalPrice && c.MaxValue >= TotalPrice) // Modified by Vietlv test vaule of boundaris (">" --> ">=")
                                        .FirstOrDefault();
                return CurrentConvertPrice;	
			}
			catch(Exception ex)
			{
				throw ex;
			}
        }
        #endregion

        #region Binhlv/GetConvertAreaID
		private ConvertArea GetConvertArea(double Area, int TypeProduct)
		{
			try
			{
				if (Area < 0) throw new NotSupportedException();
                var maxArea = eDataContext.ConvertAreas
                    .Where(e =>e.TypeID == TypeProduct)
                    .OrderByDescending(e => e.MaxValue)
                    .FirstOrDefault();
                if (Area > Convert.ToDouble(maxArea.MaxValue))
                {
                    return maxArea;
                }
                var CurrentConvertAreaID = eDataContext.ConvertAreas
                                        .Where(ca => ca.TypeID == TypeProduct)
                                        .Where(c => c.MinValue < (decimal)Area && c.MaxValue >= (decimal)Area) // Modified by Vietlv test vaule of boundaris (">" --> ">=")
                                        .FirstOrDefault();
                return CurrentConvertAreaID;

			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
        #endregion

        #region GET: /Product/Edit/5
        public ActionResult Edit(int id)
        {
            try
            {
                    // product detail
                    Product pro = eDataContext.Products.Where(p => p.ID == id).FirstOrDefault();

                    // product category
                    List<ProductCategory> categories = eDataContext.ProductCategories
                                                    .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                    .ToList();
                    
                    // city
                    List<SelectListItem> listC = eDataContext.Cities
                                                    .Select(c => new SelectListItem()
                                                    {
                                                        Value = c.ID.ToString(),
                                                        Text = c.Name
                                                    }).ToList();

                    // district
                    List<SelectListItem> listD = eDataContext.Districts
                                                    .Where(d=>d.CityID == pro.CityID)
                                                    .Select(d => new SelectListItem()
                                                    {
                                                        Value = d.ID.ToString(),
                                                        Text = d.Name
                                                    }).ToList();

                    // product attribute
                    var listPAtt = eDataContext.ProductAttributes.ToList();

                    // product attribute value
                    var listPAttID = eDataContext.ProductAttributeValues.Where(pV => pV.ProductID == id).Select(pV => pV.AttributeID).ToList();

                    // product type
                    List<SelectListItem> listType = eDataContext.ProductTypes
                                                    .Select(t => new SelectListItem()
                                                    {
                                                        Text = t.Name,
                                                        Value = t.ID.ToString()
                                                    }).ToList();

                    // product image
                    List<string> listF = Uploads.GetFile(id, Settings.Default.SiteRootPath, Settings.Default.ProductRootPath, Settings.Default.ProductFormatSubPath, pro.AddDate.Value);
                    
                // Created by VietLV (28/07/2011) (get current CostType)
                    //var isUSD = pro.UnitCost.Contains("USD");                    
                    //var currentCostType = isUSD == true ? "USD" : "VND";
                    //var currentUnistCost = pro.UnitCost.Contains("/m2/tháng") == true ? "M2M" : (pro.UnitCost.Contains("/tổng") == true ? "SUM" : "M2");
                    var listCurrency = Utils.StringToDictionary(Settings.Default.ListCurrency.ToString(), ",");
                    var listUnitCost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",");
                    var listExpireDate = Utils.StringToDictionary(Settings.Default.ProducExpire.ToString(), ",");
                    var listDirection = Utils.StringToDictionary(Settings.Default.ProductDirection.ToString(), ",");
                    
                    return View(new ProductInputModel
                    {
                        Categories = categories,
                        ListCity = listC,
                        Product = pro,
                        ListDistrict = listD,
                        CityID  = pro.CityID,
                        DistrictID = pro.DistrictID,
                        CatID = pro.CatID,
                        TypeID = pro.TypeID,
                        ListProductAtribute = listPAtt,
                        ListProductAttributeID = listPAttID,
                        ListType = listType,
                        ListFile = listF,
                        ImageRootUrl = Settings.Default.SiteRootUrl,
                        ListCurrency = listCurrency,
                        ListUnitCost = listUnitCost,
                        listProductExpire = listExpireDate,
                        listProductDirection = listDirection
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion
        
        #region POST: /Product/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, ProductInputModel m)
        {
            try
            {
                    if (ModelState.IsValid)
                    {
                        m.Product = eDataContext.Products.Where(p => p.ID == id).FirstOrDefault();
                        
                        UpdateModel(m);

                        #region cost convert
                        
                        #region Case currency is "VND"
                        if (m.Product.CurrencyID == 1)
                        {
                            //Case unit cost is VND/m2
                            if (m.Product.UnitCostID == 1 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                m.Product.TotalCost = (decimal)m.Product.Area.Value * m.Product.Cost;                     // from  m.Product.UnitCost = costTypeID + new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2)  
                            }                                                                                             // To m.Product.UnitCost =new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2);   
                            // Case unit cost is VND/m2/tháng
                            if (m.Product.UnitCostID == 2 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                //var ttCost = Convert.ToDecimal(Request["Product.Cost"]);
                                m.Product.TotalCost = (decimal)m.Product.Area.Value * m.Product.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                            }
                            // Case unit cost is VND/tổng
                            if (m.Product.UnitCostID == 3 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                m.Product.TotalCost = m.Product.Cost;
                            }
                            m.Product.CurrencyName = "VND";
                        }
                        #endregion
                        
                        #region Case currency is "USD"
                        if (m.Product.CurrencyID == 2)
                        {
                            //Case unit cost is USD/m2
                            if (m.Product.UnitCostID == 1 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Area.Value * m.Product.Cost.Value;
                            }
                            // Case unit cost is USD/m2/tháng
                            if (m.Product.UnitCostID == 2 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Area.Value * m.Product.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                            }
                            //Case unit cost is USD/Tổng
                            if (m.Product.UnitCostID == 3 && m.Product.Area.HasValue)
                            {
                                var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                                foreach (var unitcost in listUnistcost)
                                {
                                    var unitKey = Convert.ToInt32(unitcost.Key);
                                    if (unitKey == m.Product.UnitCostID) m.Product.UnitCost = unitcost.Value.ToString();
                                }
                                m.Product.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Product.Cost.Value;
                            }
                            m.Product.CurrencyName = "USD";
                        }
                        #endregion
                        eDataContext.SubmitChanges();
                        if (m.Product.TotalCost.HasValue)
                        {
							//Binhlv 
                            m.Product.ConvertPrice1 = GetConvertPrice(m.Product.TotalCost.Value, m.Product.TypeID);
                            //string conPri = (m.Product.TotalCost.Value / 1000000000).ToString();
                            //m.Product.ConvertPrice = byte.Parse(conPri.Substring(0, conPri.IndexOf(".")));
                        }
						//Binhlv
						// Khoang dien tich
						if (m.Product.Area.HasValue)
						{
							m.Product.ConvertArea1 = GetConvertArea(m.Product.Area.Value, m.Product.TypeID);
						}
                        #endregion
                        int exDate = Utils.ParseInt(Request["ExpireTime"].ToString());
                        if (exDate > 0) m.Product.ExpireDate.Value.AddDays(exDate);   
                        m.Product.ModifyBy = UserManager.GetUserId();
                        m.Product.ModifyDate = DateTime.Now;

                        eDataContext.SubmitChanges();

                        HttpPostedFileBase fileImage = Request.Files["ImagePaths"];
                        if (fileImage != null && fileImage.ContentLength > 0)
                        {
                            m.Product.ImagePath = Path.GetFileName(fileImage.FileName);
                            Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ProductRootPath), "" + m.Product.ID);
                        }
                        eDataContext.SubmitChanges();

                        #region product attribute

                        var pAtt = eDataContext.ProductAttributeValues.Where(pa => pa.ProductID == id).ToList();
                        eDataContext.ProductAttributeValues.DeleteAllOnSubmit(pAtt);
                        eDataContext.SubmitChanges();

                        ///Modified by Vietlv
                        ///Modified date: 27/08/2011
                        ///Description manage map Product with ProductAttribute
                        // Delete attribute olde
                        var listProAttribute = eDataContext.ProductAttributeValues.Where(e => e.ProductID == id).ToList();
                        eDataContext.ProductAttributeValues.DeleteAllOnSubmit(listProAttribute);
                        // insert new attribute to table ProductAttributeValue
                        foreach (var proAtt in eDataContext.ProductAttributes)
                        {
                            var isSelected = Request["ProductAtribute." + proAtt.ID] != null && Request["ProductAtribute." + proAtt.ID].ToString().Equals("false") == false ? true : false;
                            if (isSelected == true)
                            {
                                var itemAttribute = new ProductAttributeValue();
                                itemAttribute.ProductID = id;
                                itemAttribute.AttributeID = proAtt.ID;
                                itemAttribute.Value = "1";
                                eDataContext.ProductAttributeValues.InsertOnSubmit(itemAttribute);
                            }
                        }
                        eDataContext.SubmitChanges();
                        #endregion

                        #region Upload File
                        foreach (string inputTagName in Request.Files)
                        {
                            HttpPostedFileBase file = Request.Files[inputTagName];
                            if (file.ContentLength > 0 && inputTagName != "ArticleImage")
                            {
                                string filePath = string.Empty;
                                string subPath = string.Format(Settings.Default.ProductFormatSubPath, m.Product.AddDate.Value.Year, m.Product.AddDate.Value.Month, m.Product.AddDate.Value.Day, m.Product.ID);
                                if (!Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath))
                                {
                                    // If it doesn't then we just create it before going any further
                                    Directory.CreateDirectory(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath);
                                }
                                filePath = Path.Combine(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath, file.FileName);
                                file.SaveAs(filePath);
                            }
                        }
                        #endregion

                        return RedirectToAction("Index");
                    }
                    else
                    {
                        throw new Exception("Dữ liệu nhập không đúng.");

                    }
            }
            catch (Exception exp)
            {
                if (exp.Message.Contains("out of range"))
                { ViewData[Messages.MessageInfo] = "Tổng giá trị của bất động sản đã vượt quá mức con số cho phép. Vui xem xét lại!";
                return View();
                }
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
#endregion
        
        #region GET: /Article/Delete/5


        public ActionResult Delete(int id)
        {
            try
            {
                    Product pro = eDataContext.Products.SingleOrDefault(e => e.ID == id);

                    return View(pro);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
#endregion 

        #region POST: /Article/Delete/5

        [HttpPost]
        [Authorize()]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    Product pro = eDataContext.Products.SingleOrDefault(e => e.ID == id);
                    if (pro != null)
                    {
                        string subPath = string.Format(Settings.Default.ProductFormatSubPath, pro.AddDate.Value.Year, pro.AddDate.Value.Month, pro.AddDate.Value.Day, pro.ID);
                        string subThumbPath = string.Format(Settings.Default.ProductFormatSubPath, pro.AddDate.Value.Year, pro.AddDate.Value.Month, pro.AddDate.Value.Day,"Thumb\\"+ pro.ID);
                        if (Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath))
                        {
                            // If it doesn't then we just create it before going any further
                            Directory.Delete(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath, true);
                        }
                        if (Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subThumbPath))
                        {
                            // If it doesn't then we just create it before going any further
                            Directory.Delete(Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subThumbPath, true);
                        }
                        var comments = eDataContext.Comments.Where(e => e.CommentsInProducts.Where(k => k.ProductID == id).ToList().Count > 0).ToList();
                        eDataContext.CommentsInProducts.DeleteAllOnSubmit(from e in eDataContext.CommentsInProducts where e.ProductID == id select e);
                        eDataContext.Comments.DeleteAllOnSubmit(comments);
                        eDataContext.Products.DeleteOnSubmit(pro);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
#endregion
    }
}
